package com.spring.boot.sample.test2.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class IndexController {

	/**
	 * 上传测试
	 * @return
	 */
	@RequestMapping("file")
	public String file(){
		return "file";
	}
	@RequestMapping("files")
	public String files(){
		return "files";
	}
	@RequestMapping("upload")
	@ResponseBody
	public String handleFileUpload(@RequestParam("file") MultipartFile file){
		if(!file.isEmpty()){
			try {
				String fileName=file.getOriginalFilename();
				BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("d:/qrcode/"+fileName)));
				out.write(file.getBytes());
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				 return"上传失败,"+e.getMessage();
			} catch (IOException e) {
				e.printStackTrace();
				 return"上传失败,"+e.getMessage();
			}
			return "上传成功！";
		}else{
			return "上传文件失败，文件为空！";
		}
	}
	@RequestMapping("multiUpload")
	@ResponseBody
	public String multiUpload(@RequestParam("file")MultipartFile[] files){
		String fileName = null;
    	String msg = "";
    	if (files != null && files.length >0) {
    		for(int i =0 ;i< files.length; i++){
	            try {
	                fileName = files[i].getOriginalFilename();
	                byte[] bytes = files[i].getBytes();
	                BufferedOutputStream buffStream = 
	                        new BufferedOutputStream(new FileOutputStream(new File("d:/log/" + fileName)));
	                buffStream.write(bytes);
	                buffStream.close();
	                msg += "You have successfully uploaded " + fileName +"<br/>";
	            } catch (Exception e) {
	                return "You failed to upload " + fileName + ": " + e.getMessage() +"<br/>";
	            }
    		}
    		return msg;
        } else {
            return "Unable to upload. File is empty.";
        }
	}
}
